package me.ljd.yigo.mid.service;

import java.util.ArrayList;

import com.bokesoft.yigo.common.util.TypeConvertor;
import com.bokesoft.yigo.mid.base.DefaultContext;
import com.bokesoft.yigo.mid.connection.IDBManager;
import com.bokesoft.yigo.mid.service.IExtService;
import com.bokesoft.yigo.struct.datatable.DataTable;

import me.ljd.yigo.utils.DBManagerUtil2;

public class SetJoinWhereService  implements IExtService {
	/**
	 * 查询关联表的关联条件
	 * 选择join字典下拉框时调用 
	 * 参数1：本表单的表名
	 * 参数2：OID的值
	 * 参数3：joinID 
	 * 返回：join对应的条件，用作后面的跳转
	 */
	public Object doCmd(DefaultContext context, ArrayList<Object> paras) throws Throwable {
		if(paras == null || paras.size() < 3) {return null;}
		Long joinID = TypeConvertor.toLong(paras.get(2));
		String sql = "select Code from JoinOn where oid=?";
		IDBManager dbManager=context.getDBManager();
		DataTable tableJoin = dbManager.execPrepareQuery(sql, joinID);
		String code = tableJoin.getString(0);
		String[] joinArr = code.split("=");
		String tblName = (String)paras.get(0);
		String colSelect = null;
		String colWhere = null;
		if(joinArr[0].contains(tblName.toUpperCase())) {
			colSelect = joinArr[0];
			colWhere = joinArr[1];
		}else {
			colSelect = joinArr[1];
			colWhere = joinArr[0];
		}
		Object value = "";
		String sql2 = "select "+colSelect+" from "+tblName + " where oid=?";
		dbManager=DBManagerUtil2.getDBManager(1);
		try {
			DataTable table = dbManager.execPrepareQuery(sql2, paras.get(1));
			value = table.getObject(0);
		} catch (Exception e) {
			DBManagerUtil2.dsnMapClear();
			e.printStackTrace();
		}
//		context.setPara("_Table", colWhere.split("\\.")[0]);
//		context.setPara("_Column", colWhere.split("\\.")[1]);
//		context.setPara("_Value", value);
		//context.getDocument().eval
		return colWhere + "="+ value;
		//return value;
	}

}
